import React, { useState,useEffect } from 'react';
import { Form, Input, Modal, Radio,Select } from 'antd';
const { Option } = Select;
const FormItem = Form.Item;
import SelectDeviceModal from '@/pages/authority/deviceattr/components/selectDeviceModal';
export interface UpdateFormProps {
  onCancel: () => void;
  onSubmit: (values: API.DeviceLinkageRuleItem,resetForm:()=>void) => void;
  updateModalVisible: boolean;
  values: API.RoleItem;
  getAttrData: (id:number) => API.SysDeviceAttrItem;
  deviceList?:API.DeviceItem[];
}

const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};

//数字比较符
var symbolValueEnum=['>','>='];
  
  
const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  
  const [formVals] = useState<API.DeviceLinkageRuleItem>(props.values);
  console.log(props.values)
  const [form] = Form.useForm();

  const { updateModalVisible, onSubmit: handleUpdate, onCancel,getAttrData,deviceList } = props;

    
  const [selectDeviceModalVisible, handleDeviceModalVisible] = useState<boolean>(false);
  const [deviceId,setDeviceId] = useState<number|undefined>(formVals.deviceId);
  // const [attrId,setAttrId] = useState<number|undefined>(formVals.attrId);
  const [valueRole,setValueRole] = useState<string>(formVals.valueRole);
  const [symbolEnum,setSymbolEnum] = useState<string[]>(formVals.valueRole=='低于'?["<=","<"]:symbolValueEnum);
  const [deviceName,setDeviceName] = useState<string>(formVals.deviceName);
  const [attrList,setAttrList] = useState<API.SysDeviceAttrItem>([]);
  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    fieldsValue.id = formVals.id;
    fieldsValue.deviceId=deviceId;
    fieldsValue.attrId=attrId;
    handleUpdate(fieldsValue,resetForm);
 
  }

  const resetForm= async () => {
  
    form.resetFields();
  }; 
   const validatorValue = async (_: any, value: string) => {
    const promise = Promise;
    if(Number.parseInt(value)>999999999999){
      return promise.reject("值不能超过99999999999");
    }
  
    if(_.field=='maxValue'&&value<form.getFieldValue('minValue')){
      return promise.reject("最大值不能小于最小值");
    }
    return promise.resolve();
  };


  const setAttrListData = async () => {
    var attrData= await getAttrData(formVals.deviceId);
    setAttrList(attrData);
  } 
  useEffect(() => {
    setAttrListData();
  }, []);



  const changeRole =  (e) => {

    setValueRole(e.target.value);
    if(e.target.value=="高于"){
      setSymbolEnum(['>','>='])
      form.setFieldsValue("symbol",">");
    }else if(e.target.value=="低于"){
      form.setFieldsValue("symbol","<=");
      setSymbolEnum(['<=','<'])
    }else{
      form.setFieldsValue("symbol","=");
    }
  };
  return (
    <Modal
      width={640}
     
      destroyOnClose
      title="编辑任务规则"
      visible={updateModalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >


   <Form {...formLayout}
        form={form}
        initialValues={formVals}>
         <FormItem
            label="设备"
           
            rules={[{ required:true, message: '请选择设备' }]}
        >
          <Input placeholder="请选择设备" value={deviceName}   onClick={() => handleDeviceModalVisible(true)}  />
        </FormItem>
        <FormItem
          label="变量"
          name="attrId"
          rules={[{ required: true}]}
        >
          <Select placeholder="请选择">
            {attrList.map((item) => (
              <Option key={item.attrId} value={item.attrId}>
                {item.browseName}
              </Option>
            ))}
          </Select>
        </FormItem>
        {/* <FormItem
          label="状态"
          name="useState"
        >
          <Radio.Group>
            <Radio value={1} >
              启用
            </Radio>
            <Radio value={0}>
             不启用
            </Radio>
          </Radio.Group>
        </FormItem> */}
        <FormItem
          label="联动规则"
          name="valueRole"
        >
          <Radio.Group onChange={(e)=>changeRole(e)}>
            <Radio value={'高于'} >
            高于
            </Radio>
            <Radio value={'介于'}>
             介于
            </Radio>
            <Radio value={'低于'}>
             低于
            </Radio>
          </Radio.Group>
        </FormItem>
        {valueRole!='介于'?
        <FormItem
          label="数值比较符号"
          name="symbol"
          rules={[{ required: true}]}
        >
          <Select placeholder="请选择">
            {symbolEnum.map((item) => (
              <Option key={item} value={item}>
                {item}
              </Option>
            ))}
          </Select>
        </FormItem>  :null}
        {valueRole!='低于'?
        <FormItem
          label="最小值"
          name="minValue"
          
          rules={[{ required:true, message: '请输入最小值' }, { validator: validatorValue}]}
        
        >
         <Input type="number" placeholder="请输入最小值"   />
        </FormItem>
        :null}
        {valueRole!='高于'?
        <FormItem
          label="最大值"
          name="maxValue"
        rules={[{ required:true, message: '请输入最大值' }, { validator: validatorValue}]}
        
        ><Input type="number" placeholder="请输入最大值"   />
       
        </FormItem>:null}
        <FormItem
          label="或并关系"
          name="andOr"
        >
          <Radio.Group>
            <Radio value={'and'} >
              并且
            </Radio>
            <Radio value={'or'}>
              或者
            </Radio>
          </Radio.Group>
        </FormItem>
       
      </Form>
     <SelectDeviceModal
        onSubmit={async (id,name) => {
          if(id!=deviceId){
            form.setFieldsValue({attrId:null});
          }
          setDeviceId(id);
          setDeviceName(name);
          var attrData= await getAttrData(id);
          // setAttrId(undefined);
          setAttrList(attrData);
          handleDeviceModalVisible(false);
          }}
        onCancel={() => handleDeviceModalVisible(false)}
        modalVisible={selectDeviceModalVisible}
        selectionType={'radio'}
        selectedids={[deviceId]}
        deviceList={deviceList}
      />
    </Modal>
  );
};

export default UpdateForm;
